import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'


import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'

import axios from 'axios'
//配置axios的全局基本路径
axios.defaults.baseURL='http://localhost:8080/'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})

//前置拦截器
//axios携带token，由后台拦截器获取数据进行判断
axios.interceptors.request.use(config=>{
  //获取localStorage中的数据并且判断不为空就配置到请求头发送给后端拦截器判断
  let token = localStorage.getItem("token");
  if(token){
    config.headers["token"] = token;
  }
  return config;
},error=>{
  Promise.reject(error)
})

//后置拦截器
// 判断后端返回的结果
axios.interceptors.response.use(config=>{
  //标准样式
  let temp=config.data;
  //如果后端返回false那么移除localStorage中的数据并且跳转到登录页面
  if(!temp.success && temp.message==="noLogin"){
    localStorage.removeItem("token");
    localStorage.removeItem("loginInfo");
    router.push({path:"/login"});
  }
  return config;
//  返回错误样式
},error => {
  Promise.reject(error)
})

// //配置没有与后端交互页面的拦截
router.beforeEach((to, from, next) => {
  //NProgress.start();
  //  如果跳转登录页面或者店铺入驻页面就移除localStorage中的数据
  if (to.path == '/login'||to.path == "/register") {
    localStorage.removeItem("token");
    localStorage.removeItem("loginInfo");
    next()
  }else {
    //获取localStorage中的对象数据并转化为json对象
    let user = JSON.parse(localStorage.getItem('loginInfo'));
    if(!user){
      //没有登录跳转登录页面
      next({path:"/login"})
    }else {
      //正常登录后放行
      next()
    }
  }

})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

